// 引入各个功能模块
import bluetoothConnection from './bluetoothConnection'
import deviceConnection from './deviceConnection'
import deviceMeasurement from './deviceMeasurement'
import deviceReport from './deviceReport'
import ErrorTypes from './utils/errorTypes';

/**
 * 初始化函数，用于合并所有功能并返回可调用的方法
 * @param {Object} config - 配置项对象
 * @param {string} config.connectionMode - 设备连接方式，'auto' 或 'manual'
 * @param {string} config.serviceId - 设备服务 ID
 * @param {function} config.onDeviceFound - 设备发现处理函数
 * @param {function} config.characteristicMatch - 特征值匹配函数
 * @param {function} config.communicationData - 设备发送通信数据的生成函数
 * @param {function} config.reportMethod - 设备上报方式的处理函数
 * @param {function} config.errorHandler - 异常处理函数
 * @param {function} config.reportDataHandler - 上报数据处理函数
 * @returns {Object} - 包含四个功能方法的对象
 */
function BluetoothPlugin(config) {
  // 默认配置项
  const defaultConfig = {
    connectionMode: 'auto', // 'auto' or 'manual'
    serviceId: '',
    onDeviceFound: (devices, deviceList) => {
      console.log('设备发现:', devices);
      console.log('设备列表:', deviceList);
    },
    characteristicMatch: (characteristics) => {
      const writeChar = characteristics.find(c => c.properties.write);
      const notifyChar = characteristics.find(c => c.properties.notify);
      return { writeChar, notifyChar };
    },
    communicationData: () => {
      let buffer = new ArrayBuffer(6);
      let dataView = new DataView(buffer);
      dataView.setUint8(0, 0x02);
      dataView.setUint8(1, 0x40);
      dataView.setUint8(2, 0xdc);
      dataView.setUint8(3, 0x01);
      dataView.setUint8(4, 0xa1);
      dataView.setUint8(5, 0x3c);
      return buffer;
    },
    reportDataHandler: (data) => {
      return data;
    },
    reportMethod: (data) => {
      console.log('Reporting data:', data);
    },
    errorHandler: (err) => {
      console.log('Error:', err);
    }
  };
  // 合并用户配置和默认配置
  config = Object.assign({}, defaultConfig, config);

  // 初始化蓝牙连接功能
  const { initBluetooth, disconnectBluetoothAdapter } = bluetoothConnection(config);
  // 初始化设备连接功能
  const { connectDevice, startBluetoothDiscovery, stopBluetoothDiscovery, getDeviceInfo, disconnectDevice } = deviceConnection(config);
  // 初始化设备测量功能
  const { startMeasurement, setDeviceInfo, getMeasureData } = deviceMeasurement(config);
  // 初始化设备上报功能
  const { reportData, setMeasureData } = deviceReport(config);

  // 返回可调用的方法
  return {
    connectBluetooth: initBluetooth,
    disconnectBluetoothAdapter,
    startBluetoothDiscovery,
    stopBluetoothDiscovery,
    connectDevice,
    disconnectDevice,
    startMeasurement: () => {
      setDeviceInfo(getDeviceInfo())
      startMeasurement()
    },
    reportData: () => {
      setMeasureData(getMeasureData())
      reportData()
    },
  };
}

export {
  BluetoothPlugin,
  ErrorTypes
}
